package com.bosssoft.hr.train.springmvc.example.dao.impl;


import com.bosssoft.hr.train.springmvc.example.dao.UserDao;
import com.bosssoft.hr.train.springmvc.example.model.User;
import com.bosssoft.hr.train.springmvc.example.dao.UserRowMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @description 用户数据库操作具体实现
 * @author ChenTong
 * @date 2020/6/6
 */
@Repository
@Slf4j
public class UserDaoImp implements UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public int remove(Long id) {
        String sql = "DELETE FROM user WHERE id = ?";
        return jdbcTemplate.update(sql,id);
    }

    public int save(User user){
        String sql = "INSERT INTO user VALUES(?,?,?,?)";
        return jdbcTemplate.update(sql,user.getId(),user.getName(),user.getCode(),user.getPassword());

    }

    @Override
    public int update(User user) {
        String sql = "UPDATE user SET name=?,password=?,code=? WHERE id=?";
        return  jdbcTemplate.update(sql,user.getName(),user.getPassword(),user.getCode(),user.getId());

    }

    @Override
    public List<User> query() {
        log.info("DB query all");
        String sql = "SELECT * FROM user";

        return jdbcTemplate.query(sql,new UserRowMapper());
    }

    @Override
    public User queryUserByName(String username){
        log.info("DB query user by name");
        String sql = "SELECT * FROM user WHERE name=?";

        return jdbcTemplate.query(sql,new UserRowMapper(),username).get(0);

    }
}
